<script setup>
import { getHistory, setHistory, clearHistory } from "@/utils/storage";
import router from "@/router";
import { ref, onMounted } from "vue";
const search = ref("");
const history = ref([]);
const searchRef = ref(null);
// 初始化搜索历史
history.value = getHistory();
// 搜索
const goSearch = (keyword) => {
  // 如果为空字符串不进行搜索
  if (keyword.trim().length === 0) {
    return;
  }
  // 先判断搜索历史中是否有该关键词
  const index = history.value.indexOf(keyword);
  // 如果搜索历史中存在该关键词，先删除
  if (index !== -1) {
    history.value.splice(index, 1);
  }
  // 把搜索结果添加到数组的最前面
  history.value.unshift(keyword.trim());
  // 把数组存储到本地
  setHistory(history.value);
  console.log(keyword);
  // 跳转到搜索列表页
  router.push({
    path: "/search/list",
    query: {
      keyword: keyword.trim(),
    },
  });
};
// 清除搜索历史
const clear = () => {
  history.value = [];
  clearHistory();
};
const onClickLeft = () => {
  router.back();
};
const focusSearch = () => {
  searchRef.value.focus();
};
onMounted(() => {
  focusSearch();
});
</script>
<template>
  <div class="topic">
    <div class="search">
      <div class="header">
        <van-nav-bar
          title="话题搜索"
          left-arrow
          text-light
          @click-left="onClickLeft"
        />
      </div>
      <van-search
        v-model="search"
        show-action
        ref="searchRef"
        placeholder="请输入搜索关键词"
        background="#fff"
        clearable
      >
        <template #action>
          <div @click="goSearch(search)">搜索</div>
        </template>
      </van-search>

      <!-- 搜索历史 -->
      <div class="search-history">
        <div class="title">
          <span>最近搜索</span>
          <van-icon name="delete-o" size="1rem" @click="clear()" />
        </div>
        <div class="list" v-if="history.length > 0">
          <div
            class="list-item"
            v-for="item in history"
            :key="item"
            @click="goSearch(item)"
          >
            {{ item }}
          </div>
        </div>
        <div class="empty" v-else>暂无历史数据</div>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
.search {
  .searchBtn {
    background-color: skyblue;
    color: #fff;
  }
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }
  .list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }
  .list-item {
    width: 30%;
    text-align: center;
    padding: 7px;
    line-height: 15px;
    border-radius: 50px;
    background: #fff;
    font-size: 13px;
    border: 1px solid #efefef;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
  .empty {
    text-align: center;
    font-size: 14px;
    color: #999;
    margin-top: 20px;
  }
}
</style>
